<template>
  <div
    ref="mycharts"
    id="mycharts"
    style="width: 98%; height: 50vh; min-height: 350px"
  ></div>
</template>
<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted, watch, ref, reactive, computed } from "vue-demi";
import { useRoute } from "vue-router";

const _useRoute = useRoute();

const options = reactive([
  {
    name: "测试数据1",
    type: "line",
    showSymbol: false,
    smooth: true,
    data: [
      ["2000-06-05", 116],
      ["2000-06-16", 129],
      ["2000-07-07", 135],
      ["2000-07-18", 86],
      ["2000-08-09", 73],
      ["2000-08-20", 85],
    ],
  },
  {
    name: "测试数据2",
    type: "line",
    showSymbol: false,
    smooth: true,
    data: [
      ["2000-06-05", 200],
      ["2000-07-06", 106],
      ["2000-08-07", 201],
      ["2000-09-08", 300],
    ],
  },
]);

const chartsTitle = computed(() => {
  return _useRoute.query.title || "动态x轴，堆叠折线，可以多条数据同处于一张表";
});

let myChart = ref(<any>{});

const clearOptions = function () {
  options.length = 0;
};

const initCharts = () => {
  // 需要获取到element,所以是onMounted的Hook
  // 绘制图表
  myChart.setOption({
    //设置线条的颜色，后面是个数组
    color: [rgbColor(), rgbColor(), rgbColor(), rgbColor(), rgbColor()],
    toolbox: {
      feature: {
        saveAsImage: {},
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    title: {
      text: chartsTitle.value,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    xAxis: {
      type: "time",
      name: "时间",
      //线条和y轴是否有缝隙
      boundaryGap: false,
      scale: true,
      formatter: function (value: string) {}, //这里可以格式化你的刻度数据
    },
    yAxis: {
      type: "value",
      name: "吨价/元",
      formatter: function (value: string) {}, //这里可以格式化你的刻度数据
    },
    series: options,
  });
};

// 随机线颜色
function rgbColor() {
  let r = Math.floor(Math.random() * 256);
  let g = Math.floor(Math.random() * 256);
  let b = Math.floor(Math.random() * 256);
  let rgb = `rgb(${r},${g},${b})`;
  return rgb;
}

onMounted(() => {
  myChart = echarts.init(document.getElementById("mycharts"), null, {
    locale: "ZH",
  });
  initCharts();
  window.addEventListener("resize", () => {
    // 自适应大小
    myChart.resize();
  });
});
watch(
  () => _useRoute.fullPath,
  () => {
    clearOptions();
    // 这里做一些什么
    myChart.setOption({ series: JSON.parse(_useRoute.query.series.toString()) });
  }
);
</script>
<style lang="scss">
.main-home {
  height: 100%;
  font-size: $font-size-normal;
}
</style>
